<template>
  <div :class="{'mobile-create': showMobilePage}" class="select-container-box">
    <el-row>
      <el-form ref="editForm" :model="editUserForm" :label-position="showMobilePage ? 'left' : 'right'" class="edit-user" label-width="100px">
        <div>
          <Title :title="title" class="mb-16"/>
          <el-form-item label="角色名称" prop="userName" class="is-required form-box-item">
            <span v-if="isDisabled" class="textValue">{{ editUserForm.roleName }}</span>
            <el-input v-if="!isDisabled" v-model="editUserForm.roleName" class="edit-form-name" size="small" placeholder="请输入角色名称" name="roleName" type="text" />
            <div class="bottom-checkbox">
              <el-checkbox v-model="editUserForm.isDefaultRole">设为默认角色</el-checkbox>
            </div>
          </el-form-item>
          <el-form-item label="配置职位" prop="status" class="form-box-item no-required">
            <selectWithUserLoad
              v-model="editUserForm.post"
              :hide-select-list="hideSelectList || []"
              :loadmore-method="getPost()"
              :per-page="100"
              :collapse-tags="false"
              :disabled="editUserForm.isDefaultRole"
              :class="editUserForm.isDefaultRole && 'disabled-cursor'"
              multiple
              style="width:240px;"
              class="width240"
              placeholder="请选择默认配置职位"
              key-name="id"
              label-name="name"
              filterable
              clearable
            />
          </el-form-item>
          <el-form-item label="配置部门" prop="status" class="form-box-item no-required">
            <CascaderSelect
              v-model="editUserForm.departmentIds"
              :options="deptTreeList"
              children="children"
              placeholder="请选择默认配置部门"
              popper-class="cascader-depts"
              class="width240"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status" class="is-required form-box-item">
            <el-switch
              v-model="editUserForm.status"
              :active-value="1"
              :inactive-value="0"/>
          </el-form-item>
          <el-form-item label="可用权限" prop="status" class="is-required mobile-select-auth">
            <selectAuth ref="select-auth" :show-expend-all="true" :is-disabled="isEditDisabled()" :default-auth="defaultParams.auth" style="padding-top: 3px;" @changeAuth="changeAuth"/>
          </el-form-item>
        </div>
      </el-form>
    </el-row>
    <fixed-pagination>
      <div class="center">
        <el-button v-if="!isEditDisabled() || isCopy" :loading="loading" size="small" type="primary" @click="toSave('editUserForm')">提交</el-button>
        <el-button type="info" class="cancel-btn-style" size="small" @click="toClear()">返回</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>
<script>
import selectAuth from '@/components/AuthPage/selectAuth';
import Title from '@/components/Title';
import { createRole, editRole, getRoleDetail, getPostList } from '@/api/auth';
import ElMessage from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import CascaderSelect from '@/components/Tool/module/cascaderSelect';
import { mapState } from 'vuex';
import mobileCreate from '@/mixins/mobileCreate';
import { getDepartmentAll } from '@/api/config';

export default {
  components: { selectAuth, Title, selectWithUserLoad, CascaderSelect },
  mixins: [mobileCreate],
  data() {
    return {
      editUserForm: {
        roleName: '',
        auth: [],
        post: [],
        isDefaultRole: false,
        status: 1,
        departmentIds: []
      },
      authDataWord: [],
      defaultParams: {},
      title: '创建角色',
      isDisabled: false,
      loading: false,
      isEdit: false,
      isCopy: false,
      hideSelectList: [],
      deptTreeList: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    })
  },
  watch: {
    'editUserForm.isDefaultRole'(val) {
      val && this.$set(this.editUserForm, 'post', []);
    }
  },
  created() {
    const roleId = this.$route.params.roleId;
    const isCopy = this.$route.query.copy;
    if (roleId) {
      this.title = '编辑角色';
      this.isEdit = true;
      this.isCopy = isCopy;
      this.roleId = roleId;
      this.getDetailData(roleId);
    } else {
      this.defaultParams = {};
      this.isEdit = false;
      this.title = '创建角色';
    }
    this.queryDeptTreeList();
  },
  methods: {
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      });
    },
    async getDetailData(roleId) {
      try {
        const result = await getRoleDetail({ id: roleId });
        if (result.code === 200 && result.data) {
          const defaultParams = result.data;
          this.editUserForm.roleName = defaultParams.roleName;
          this.editUserForm.auth = defaultParams.auth;
          this.editUserForm.post = defaultParams.post ? defaultParams.post.split(',') : [];
          this.editUserForm.departmentIds = defaultParams.departmentIds ? defaultParams.departmentIds.split(',') : [];
          this.editUserForm.status = defaultParams.status;
          this.editUserForm.isDefaultRole = !!defaultParams.isDefaultRole;
          if (this.$refs['select-auth']) this.$refs['select-auth'].setDefault(defaultParams.auth);
          this.defaultParams = defaultParams;

          if (this.isCopy) {
            this.editUserForm.roleName += '-副本';
          }
          if (this.editUserForm.post) {
            this.hideSelectList = this.editUserForm.post.map(i => {
              return { id: i, name: i };
            });
          }
        }
      } catch (error) {
        console.log(error);
      }
    },
    changeAuth({ authDataID, authDataWord }) {
      this.editUserForm.auth = authDataID;
      this.authDataWord = authDataWord;
    },
    toSave() {
      const editForm = this.editUserForm;
      if (editForm.roleName === '') {
        ElMessage.warning('请填写角色名称');
        return;
      }
      if (!editForm.auth || editForm.auth.length <= 0) {
        ElMessage.warning('请选择权限');
        return;
      }
      const mutexMedium = this.authDataWord.filter(i => i.indexOf('medium:medium:') >= 0);
      const mutexSale = this.authDataWord.filter(i => i.indexOf('medium:sale:') >= 0);
      if (mutexMedium.length > 0 && mutexSale.length > 0) {
        ElMessage.warning('媒介管理：销售与执行的订单展示权限只能二选一！');
        return;
      }
      const params = {
        authIds: editForm.auth.join(','),
        post: editForm.post.join(','),
        roleName: editForm.roleName,
        status: editForm.status,
        isDefaultRole: editForm.isDefaultRole,
        departmentIds: editForm.departmentIds.join(',')
      };
      this.loading = true;
      if (this.roleId && !this.isCopy) {
        params.roleId = this.roleId;
        this.editData(params);
      } else {
        this.createData(params);
      }
    },
    async editData(params) {
      try {
        const res = await editRole(params);
        this.loading = false;
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '修改成功'
          });
          this.toClear();
        } else {
          this.$message({
            type: 'error',
            message: res.message
          });
        }
      } catch (error) {
        this.loading = false;
      }
    },
    async createData(params) {
      try {
        const res = await createRole(params);
        this.loading = false;
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '新增成功'
          });
          this.$store.dispatch('GetInfo');
          this.toClear();
        } else {
          this.$message({
            type: 'error',
            message: res.message
          });
        }
      } catch (error) {
        this.loading = false;
        console.log(error);
      }
    },
    toClear() {
      this.$router.push({
        name: 'userAuthManage'
      });
    },
    isEditDisabled() {
      const roleId = Number(this.roleId);
      if (this.isEdit && !this.isCopy) {
        if (hasRouteAuth('auth:operator:adminEdit')) return false;
        if (!hasRouteAuth('auth:operator:edit')) return true;
        if (this.userInfo.userName === '管理员') return false;
        const roleListArr = this.userInfo.roleList || [];
        const ids = roleListArr.map(i => i.roleId);
        return !ids.includes(roleId);
      } else {
        return false;
      }
    },
    getPost() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.keyword = '';
          if (params.userName) params.keyword = params.userName;
          delete params.userName;
          delete params.name;
          getPostList(params).then(res => {
            if (res.data && res.data.items) {
              res.data.items = res.data.items.map(j => {
                return {
                  id: j,
                  name: j
                };
              });
            }
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.width240 {
  ::v-deep {
    .el-cascader {
      width: 240px;
      .el-input__suffix {
        display: flex;
        align-items: center;
      }
      .el-input__inner {
        &::-webkit-input-placeholder {
          color: #c0c4cc !important;
        }
      }
    }
  }
}
.select-container-box {
  margin: 16px;
  background-color: #fff;
  padding: 24px;
  min-height: calc(100vh - 80px);
  .edit-user {
    & ::v-deep {
      .el-form-item__label {
        font-size: 14px !important;
      }
      .edit-form-name {
        width: 240px;
        .el-tag {
          color: #406eff;
          background-color: #eff3fb;
        }
      }
    }
    .form-box-item {
      .bottom-checkbox {
        display: inline-block;
        margin-left: 12px;
        ::v-deep .el-checkbox__label {
          font-size: 12px;
          padding-left: 4px;
        }
        ::v-deep .el-checkbox {
          color: #333;
        }
      }
      .disabled-cursor {
        & ::v-deep {
          input, .el-select__tags, .el-input__suffix, .el-select__caret {
            cursor: not-allowed;
          }
        }
      }
      & ::v-deep {
        .el-form-item {
          margin-bottom: 20px !important;
          .el-input, .el-input__inner {
            width: 320px;
            height: 32px !important;
          }
          .textValue, .el-checkbox {
            margin-left: 10px;
          }
          .el-checkbox__input.is-checked .el-checkbox__inner {
            background-color: #515151;
            border-color: #515151;
          }
          .el-checkbox__input.is-checked + .el-checkbox__label {
            color: #515151;
          }
          .el-checkbox__inner {
            border-color: #515151;
          }
          .el-select__caret.el-input__icon.el-icon-arrow-up {
            line-height: 32px;
          }
        }
      }
    }
  }
}
.mobile-create {
  .mobile-select-auth {
    display: flex;
    flex-wrap: wrap;
    & ::v-deep {
      .el-form-item__content {
        margin-left: 10px !important;
        width: 100%;
      }
      .expend-all-btn {
        left: unset !important;
        right: 0px;
        top: -28px !important;
      }
    }
  }
}
</style>
